Ext.namespace('eddy.office');

eddy.office.module = function(tab) {
	this.main = tab;
	this.init();
}

Ext.extend(eddy.office.module, Ext.util.Observable, {
	init: Ext.emptyFn
});

eddy.office.app = function() {
	this.cachedModuls = [];
	this.init();
}

Ext.extend(eddy.office.app, Ext.util.Observable, {
	init: function() {
		this.top = new Ext.Panel({
			height: 35,
			region: 'north',
			contentEl:'SystemName-div',
			border: false
		})
		
		this.tree = new Ext.tree.TreePanel({
			region: 'west',
			margins: '0 0 0 5',
			width: 250,
			split: true,
			loader: new Ext.tree.TreeLoader({
				url: 'data/tree.txt',
				requestMethod: 'GET'
			}),
			root: new Ext.tree.AsyncTreeNode({
				id: 'root',
				text: '功能菜单',
				expanded: true
			})
		});
		
		this.tree.on('click', this.clickTree, this);
		var tab = new Ext.Panel({
			title: '首页',
			id: 'index',
			autoLoad: 'index.html',
			layout: 'fit'
		});
		
		this.mainTab = new Ext.TabPanel({
			region: 'center',
			margins: '0 5 0 0',
			activeTab: 0,
			items:[tab]
		});
		this.mainTab.on('tabchange', this.changeTab, this);
		
		var viewport = new Ext.Viewport({
			layout: 'border',
			items: [this.tree, this.mainTab,this.top]
		});
		this.loadMask = new Ext.LoadMask(this.mainTab.body)
	},
	
	changeTab: function(p, t) {
		if(!t)
			return;
			
		var id = t.id.replace('tab-', '');
		var node = this.tree.getNodeById(id);
		if(node) {
			this.tree.getSelectionModel().select(node);
		}
		else {
			this.tree.getSelectionModel().clearSelections();
		}
	},
	
	clickTree: function(node) {
		if(!node.isLeaf()) return false;
		var id = 'tab-' + node.id;
		var tab = Ext.getCmp(id);
		if(!tab) {
			this.mainTab.setActiveTab(tab);
			this.loadModel(node.attributes, tab);
		} else {
			this.mainTab.setActiveTab(tab);
		}
	},
	
	findCachedModul: function(modulId) {
		for(var i = 0; i < this.cachedModuls.length; i++) {
			if( this.cachedModuls[i].id == modulId)
				return  this.cachedModuls[i].module;
		}
	},
	
	addModul: function( module, nodeAttr) {
		var moduleInstance = new module();  
        this.mainTab.add({
			id: nodeAttr.id,
			title: nodeAttr.text,
			closable: true,
			layout: 'fit',
			items:[moduleInstance]
		}).show();
	},
	
	loadModel: function(nodeAttr, tab) {
		var model = this.findCachedModul(nodeAttr.id);
		if(model) {
			this.addModul(model, nodeAttr);
		}
		else {
			this.loadMask.show();
			Ext.Ajax.request({
				method: 'GET',
				url: 'modules/' + nodeAttr.id + '.js',
				scope: this,
				success: function(resp) {
					var module = eval(resp.responseText);
		        	this.cachedModuls.push({id:nodeAttr.id, module:module});
			        this.addModul(module, nodeAttr);
					this.loadMask.hide();
				}
			});
		}
	}
});

Ext.onReady(function() {
	Ext.QuickTips.init();
	myApp = new eddy.office.app();
});
